/*
 * @Author: humengchuan 531537052@qq.com
 * @Date: 2025-01-05 22:57:52
 * @LastEditors: humengchuan 531537052@qq.com
 * @LastEditTime: 2025-01-06 09:56:17
 * @FilePath: \project-my\vue-mall\src\directives\index.ts
 * @Description: 
 */
import { App, DirectiveBinding } from 'vue';

export const lazyPlugin = {
    install(app: App) {
        app.directive('img-lazy', {
            mounted(el: HTMLImageElement, binding: DirectiveBinding<string>) {
                const observer = new IntersectionObserver(([{ isIntersecting }]) => {
                    if (isIntersecting) {
                        try {
                            el.src = binding.value;
                        } catch (error) {
                            console.error('Failed to set image src:', error);
                        } finally {
                            observer.unobserve(el);
                        }
                    }
                }, {
                    threshold: 0.01
                });
                observer.observe(el);
            }
        });
    }
};